﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Pipra.Math.Geometry
{
    /// <summary>
    /// A geometry which is a collection of line strings.
    /// </summary>
    public class MultiLineString2 :
        Collection<LineString2>,
        IPlanarGeometry<double>,
        IHasMagnitude<double>,
        IEquatable<MultiLineString2>,
        IIntersectable<Point2>,
        IHasDistance<double,Point2>,
        IContainable<Mbr>,
        ICloneable,
        ISelfIntersectable
    {

        public static bool operator ==(MultiLineString2 a, MultiLineString2 b)
        {
            return ReferenceEquals(a, b) || (!ReferenceEquals(null, a) && a.Equals(b));
        }

        public static bool operator !=(MultiLineString2 a, MultiLineString2 b)
        {
            return !ReferenceEquals(a, b) && (ReferenceEquals(null, a) || !a.Equals(b));
        }

        /// <summary>
        /// Constructs a new empty multi line string.
        /// </summary>
        public MultiLineString2() { }
        /// <summary>
        /// Constructs a new empty line string expecting the given number of line strings.
        /// </summary>
        /// <param name="expectedCapacity">The expected number of line strings.</param>
        public MultiLineString2(int expectedCapacity)
            : base(new List<LineString2>(expectedCapacity)) { }
        /// <summary>
        /// Constructs a new multi line string containing the given line strings.
        /// </summary>
        /// <param name="lineStrings">The line strings.</param>
        public MultiLineString2(IEnumerable<LineString2> lineStrings)
            : base(null == lineStrings ? new List<LineString2>() : new List<LineString2>(lineStrings)) { }
        /// <summary>
        /// Constructs a new multi line string containing the given line strings as point collections.
        /// </summary>
        /// <param name="lineStrings">The line strings as point collections.</param>
        public MultiLineString2(IEnumerable<IEnumerable<Point2>> lineStrings)
            : this(null == lineStrings ? null : lineStrings.Select(penum => new LineString2(penum))) { }

        /// <summary>
        /// Calculates the distance between this multi line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(Point2 p)
        {
            return System.Math.Sqrt(DistanceSquared(p));
        }
        /// <summary>
        /// Calculates the distance between this multi line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(IPoint2<double> p)
        {
            return Distance(new Point2(p));
        }
        /// <summary>
        /// Calculates the squared distance between this multi line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(Point2 p)
        {
            return (
                1 == Count
                ? this[0].DistanceSquared(p)
                : (
                    Count > 1
                    ? this.Min(ls => ls.DistanceSquared(p))
                    : Double.NaN
                )
            );
        }
        /// <summary>
        /// Calculates the squared distance between this multi line string and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(IPoint2<double> p)
        {
            return DistanceSquared(new Point2(p));
        }
        /// <summary>
        /// Determines if a point intersects this multi line string.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this multi line string.</returns>
        public bool Intersects(Point2 p)
        {
            return Enumerable.Any(this, ls => ls.Intersects(p));
        }
        /// <summary>
        /// Determines if a point intersects this multi line string.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this multi line string.</returns>
        public bool Intersects(IPoint2<double> p)
        {
            return Intersects(new Point2(p));
        }
        /// <summary>
        /// Calculates a minimum bounding rectangle for this multi line string.
        /// </summary>
        /// <returns>A minimum bounding rectangle.</returns>
        public Mbr GetMbr()
        {
            if (Count > 0)
            {
                Mbr mbr = this[0].GetMbr();
                for (int i = 1; i < Count; i++)
                {
                    mbr = mbr.Union(this[i].GetMbr());
                }
                return mbr;
            }
            return Mbr.Invalid;
        }
        IMbr<double> IHasMbr<double>.GetMbr()
        {
            return GetMbr();
        }
        /// <summary>
        /// Calculates the centroid.
        /// </summary>
        /// <returns>A centroid.</returns>
        public Point2 GetCentroid()
        {
            int lasti = Count - 1;
            if (lasti > 0)
            {
                double msum = 0;
                double xsum = 0;
                double ysum = 0;
                foreach (LineString2 ls in this)
                {
                    if (ls.Count > 0)
                    {
                        double m = ls.GetMagnitude();
                        Point2 p = ls.GetCentroid();
                        xsum += p.X * m;
                        ysum += p.Y * m;
                        msum += m;
                    }
                }
                if (0 != msum)
                {
                    return new Point2(xsum / msum, ysum / msum);
                }
            }
            return lasti == 0 ? this[0].GetCentroid() : Point2.Invalid;
        }
        IPoint2<double> IHasPlanarCentroid<double>.GetCentroid()
        {
            return GetCentroid();
        }
        /// <summary>
        /// Calculates the magnitude of this multi line string.
        /// </summary>
        /// <returns>The magnitude.</returns>
        public double GetMagnitude()
        {
            return (
                1 == Count
                ? this[0].GetMagnitude()
                : (
                    Count > 1
                    ? this.Sum(ls => ls.GetMagnitude())
                    : 0
                )
            );
        }
        /// <summary>
        /// Calculates the squared magnitude of this multi line string.
        /// </summary>
        /// <returns>The magnitude.</returns>
        public double GetMagnitudeSquared()
        {
            double m = GetMagnitude();
            return m * m;
        }
        /// <summary>
        /// Clones this multi line string.
        /// </summary>
        /// <returns>A multi line string.</returns>
        public MultiLineString2 Clone()
        {
            return new MultiLineString2(this);
        }
        object ICloneable.Clone()
        {
            return Clone();
        }
        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(MultiLineString2 other)
        {
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            if (ReferenceEquals(null, other))
            {
                return false;
            }
            if(Count == other.Count)
            {
                for(int i = 0; i < Count; i++)
                {
                    if(!this[i].Equals(other[i]))
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        public override bool Equals(object obj)
        {
            return null != obj
                && (
                    (obj is MultiLineString2 && Equals(obj as MultiLineString2))
                )
            ;
        }

        public override int GetHashCode()
        {
            return GetMbr().GetHashCode() ^ -700084810;
        }


        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            string result = String.Concat("MultiLineString, ", Count, " LineString");
            return 1 != Count ? String.Concat(result, 's') : result;
        }

        /// <summary>
        /// Determines if the given MBr contains this multi line string.
        /// </summary>
        /// <param name="mbr">The mBR to test.</param>
        /// <returns>True if this multi line string is within the given MBR.</returns>
        public bool Within(Mbr mbr)
        {
            return GetMbr().Within(mbr);
        }
        /// <summary>
        /// Determines if the given MBr contains this multi line string.
        /// </summary>
        /// <param name="mbr">The mBR to test.</param>
        /// <returns>True if this multi line string is within the given MBR.</returns>
        public bool Within(IMbr<double> mbr)
        {
            return GetMbr().Within(mbr);
        }

        /// <summary>
        /// Determines if this multi line string is self-intersecting.
        /// </summary>
        /// <returns>True if self-intersecting.</returns>
        public bool IsSelfIntersecting()
        {
            throw new NotImplementedException();
        }
    }
}
